import React, { PureComponent } from 'react';
import { Layout, Menu, Icon } from 'antd';
import classNames from 'classnames';
import styles from './SiderMenu.less';
import { isUrl } from '@/utils/utils';
import Link from 'umi/link';
import { navTheme } from '../defaultSettings';
// import PageLoading from '@/components/PageLoading';

const { Sider } = Layout;
const SubMenu = Menu.SubMenu;

const getIcon = icon => {
  if (typeof icon === 'string') {
    if (isUrl(icon)) {
      return <Icon component={() => <img src={icon} alt="icon" className={styles.icon} />} />;
    }
    return <Icon type={icon} />;
  }
  return icon;
};

const getDefaultCollapsedSubMenus = props => {
  const {
    location: { pathname },
    breadcrumbNameMap,
  } = props;
  let openKeys = [];
  const pushParent = (breadcrumbNameMap, path) => {
    try {
      breadcrumbNameMap.forEach(item => {
        if (item.children && item.children.length > 0) {
          item.children.forEach(child => {
            if (child.path === path && path !== '/') {
              openKeys.push(item.path);
              pushParent(breadcrumbNameMap, item.path);
              throw new Error('EndIterative');
            }
          });
        }
      });
    } catch { }
  };
  pushParent(breadcrumbNameMap, pathname);
  return openKeys;
};

class SiderMenu extends PureComponent {

  state = {
    openKeys: getDefaultCollapsedSubMenus(this.props),
  };

  static getDerivedStateFromProps(props, state) {
    const { breadcrumbNameMap } = state;
    if (props.breadcrumbNameMap !== breadcrumbNameMap) {
      return {
        breadcrumbNameMap: props.breadcrumbNameMap,
        openKeys: getDefaultCollapsedSubMenus(props),
      };
    }
    return null;
  }

  conversionPath = path => {
    if (path && path.indexOf('http') === 0) {
      return path;
    }
    return `/${path || ''}`.replace(/\/+/g, '/');
  };

  // 获得菜单子节点
  getMenuItems = menusData => {
    if (!menusData) {
      return [];
    }
    return menusData
      .filter(item => item.name && !item.hideInMenu)
      .map(item => this.getSubMenuOrItem(item))
      .filter(item => item);
  };

  getSubMenuOrItem = item => {
    if (item.children && !item.hideChildrenInMenu && item.children.some(child => child.name)) {
      const { name } = item;
      return (
        <SubMenu
          title={
            item.icon ? (
              <span>
                {getIcon(item.icon)}<span>{name}</span>
              </span>
            ) : (name)
          }
          key={item.path}
        >
          {this.getMenuItems(item.children)}
        </SubMenu>
      );
    }
    return <Menu.Item key={item.path}>{this.getMenuItemPath(item)}</Menu.Item>;
  };

  getMenuItemPath = item => {
    const { name } = item;
    const itemPath = this.conversionPath(item.path);
    const icon = getIcon(item.icon);
    const { target } = item;
    // Is it a http link
    if (/^https?:\/\//.test(itemPath)) {
      return (
        <a href={itemPath} target={target}>
          {icon}
          <span>{name}</span>
        </a>
      );
    }
    const { location } = this.props;
    return (
      <Link
        to={itemPath}
        target={target}
        replace={itemPath === location.pathname}
      >
        {icon}
        <span>{name}</span>
      </Link>
    );
  };

  // 菜单展开处理：展开当前，收起其他
  handleOpenChange = openKeys => {
    if (openKeys.length === 0 || openKeys.length === 1) {
      this.setState({
        openKeys
      });
      return;
    }
    const lastOpenKey = openKeys[openKeys.length - 1];
    if (lastOpenKey === openKeys[0]) {
      this.setState({
        openKeys
      });
    } else {
      this.setState({
        openKeys: [lastOpenKey],
      });
    }
  };

  render() {
    const { collapsed, menuData, location } = this.props;
    const { openKeys } = this.state;
    const logo = '';
    // collapsed = true时，不设置openKeys，antd自行处理
    const defaultProps = collapsed ? {} : { openKeys };
    const siderClassName = classNames(styles.sider, {
      [styles.light]: navTheme === 'light',
    });
    return (
      <Sider className={siderClassName} style={{
        overflow: 'auto', height: '100vh', position: 'fixed', left: 0,
      }}
        trigger={null}
        collapsible
        collapsed={collapsed}
      >
        <div className={styles.logo} id="logo">
          <Link to="/">
            <img src={logo} alt="logo" />
            <h1>Blue</h1>
          </Link>
        </div>
        <Menu theme={navTheme}
          defaultSelectedKeys={[location.pathname]}
          mode="inline"
          onOpenChange={this.handleOpenChange}
          {...defaultProps}
        >
          {this.getMenuItems(menuData)}
        </Menu>
      </Sider>
    );
  }
}

export default SiderMenu;
